<?php
/**
 * Hesperos library for Zend Framework
 *
 * This script is protected by copyright. It's use, copying, modification
 * and distribution without written consent of the author is prohibited.
 *
 * @category    Hesperos
 * @package     View
 * @subpackage  Heleper
 * @author      Krzysztof Kardasz <krzysztof.kardasz@gmail.com>
 * @copyright   Copyright (c) 2011 Krzysztof Kardasz
 * @license     http://www.gnu.org/licenses/lgpl-3.0.txt  GNU Lesser General Public
 * @version     1.0 $Id$
 * @link        http://code.google.com/p/hesperos/
 */

/**
 * Pomocnik widoku, ucinanie tekstu
 *
 * @category    Hesperos
 * @package     View
 * @subpackage  Heleper
 * @author      Krzysztof Kardasz <krzysztof.kardasz@gmail.com>
 * @copyright   Copyright (c) 2011 Krzysztof Kardasz
 * @version     1.0 $Id$
 */
class Hesperos_View_Helper_Truncate  extends Zend_View_Helper_Abstract
{
    const ENCODING = 'utf-8';

    /**
     * Truncates (ocinacz tekstu) text.
     *
     * Obcina string o zadana dlugosc $length i zwraca poprawiony ciag
     *
     * @param string  $text ciąg znaków
     * @param integer $length maksymalna długość
     * @param string  $ending zakończenie
     * @param boolean $exact
     *
     * @return string Trimmed string.
     * @access public
     */
    public function truncate($text, $length, $ending = '...', $exact = true)
    {
        if (mb_strlen($text, self::ENCODING) <= $length) {
            return $text;
        } else {
            $truncate = mb_substr ($text, 0, $length - mb_strlen($ending, self::ENCODING), self::ENCODING);

            if (!$exact) {
                $spacepos = mb_strrpos($truncate, ' ', 0, self::ENCODING);
                if (isset($spacepos)) {
                    return mb_substr($truncate, 0, $spacepos, self::ENCODING) . $ending;
                }
            }
            return $truncate . $ending;
        }
    }
}